#include"Queue.h"

void QueueInit(Queue* q)
{
	assert(q);

	q->Front = NULL;
	q->Rear = NULL;
	q->size = 0;
}

void QueueDestroy(Queue* q)
{
	assert(q);

	QNode* cur = q->Front;
	while (cur)
	{
		QNode* del = cur;
		cur = cur->next;
		free(del);
	}

	q->Front = q->Rear = NULL;
	q->size = 0;
}

void QueuePush(Queue* q, QDataType x)
{
	assert(q);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (!newnode)
	{
		perror("malloc error");
		exit(-1);
	}

	newnode->data = x;
	newnode->next = NULL;

	if (q->Rear == NULL)
	{
		q->Front = q->Rear = newnode;
	}
	else
	{
		q->Rear->next = newnode;
		q->Rear = newnode;
	}

	q->size++;
}

void QueuePop(Queue* q)
{
	assert(!QueueEmpty(q));
	assert(q);

	QNode* del = q->Front;
	if (!q->Front->next)
	{
		free(del);
		q->Front = q->Rear = NULL;
	}
	else
	{
		q->Front = q->Front->next;
		free(del);
	}
	
	q->size--;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->Front->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->Rear->data;
}

bool QueueEmpty(Queue* q)
{
	assert(q);

	return q->Front == NULL && q->Rear == NULL;
}

int QueueSize(Queue* q)
{
	assert(q);

	return q->size;
}